//
//  LoginViewController.m
//  FootPrint
//
//  Created by alex tao on 2/25/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "LoginViewController.h"
#import "RegistarViewController.h"
#import "LoginRequest.pb.h"
#import "LoginResponse.pb.h"

#import "Descriptor.pb.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _parser = [[CommonParser alloc]init];
        _pwdParser = [[PwdFoundParser alloc]init];
        _pwdParser.delegate = self;
    }
    return self;
}

- (void)dealloc
{
    [_parser release];
    [_pwdParser release];
    
    [_nameText release];
    [_passText release];
    [_contentScroll release];
    [_segmentControl release];
    [_textName release];
    [_textPwd release];
    [_btnRegister release];
    [_btnLogin release];
    [_phoneText release];
    [_btnPwd release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [_segmentControl setSelectedSegmentIndex:0];
    flag = 0;
    [_nameText setPlaceholder: @"请输入手机号"];
    [_passText setPlaceholder: @"请输入密码"];
    
    [_textName setText:@"手机号:"];
    [_textPwd setText:@"密码:"];
    
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBarHidden = YES;
    
    UIImage* imgNormal =[[UIImage imageNamed:@"btn_bg_normal.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
    UIImage* imgPress =[[UIImage imageNamed:@"btn_bg_press.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
    
    
    [_btnLogin setBackgroundImage:imgNormal forState:UIControlStateNormal];
    [_btnLogin setBackgroundImage:imgPress forState:UIControlStateHighlighted];
    [_btnPwd setBackgroundImage:imgNormal forState:UIControlStateNormal];
    [_btnPwd setBackgroundImage:imgPress forState:UIControlStateHighlighted];
    
    // add a gesture, when tap in the blank area, hide the keyboard
    UITapGestureRecognizer *tapGr = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)] autorelease];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
    
}

- (void) viewTapped:(UITapGestureRecognizer*)tapGr{
    [_nameText resignFirstResponder];
    [_passText resignFirstResponder];
    [_contentScroll setContentOffset:CGPointZero animated:YES];
}

- (void) swithToIndex:(int) index {

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)swith:(UISegmentedControl *)sender {
    
    if([sender selectedSegmentIndex] == 0){
    
        flag = 0;
        [_nameText setPlaceholder:@"请输入手机号"];
        [_textName setText:@"手机号:"];
        
        [_nameText setText:@""];
        [_passText setText:@""];
        [_nameText resignFirstResponder];
        [_passText resignFirstResponder];
        [_contentScroll setContentOffset:CGPointZero animated:YES];
        
    } else if([sender selectedSegmentIndex] == 1) {
        
        flag = 1;
        [_nameText setPlaceholder: @"请输入账号"];
        [_textName setText:@"账号:"];
        
        [_nameText setText:@""];
        [_passText setText:@""];
        [_nameText resignFirstResponder];
        [_passText resignFirstResponder];
        [_contentScroll setContentOffset:CGPointZero animated:YES];
    }
}


- (IBAction) hideKeyBord {

    [_passText resignFirstResponder];
    [_contentScroll setContentOffset:CGPointZero animated:YES];
}


- (IBAction)goNext {
    
    [_passText becomeFirstResponder];
}


- (IBAction)registar {
    RegistarViewController * regVC = [[[RegistarViewController alloc] initWithNibName:@"RegistarViewController" bundle:nil] autorelease];
    [self.navigationController pushViewController:regVC animated:YES];
}

- (IBAction)login
{
    NSString * nameOrPhone = _nameText.text;
    NSString * pass = _passText.text;
    
    if (nameOrPhone.length == 0 || pass.length == 0) {
        [[[iToast makeText:@"用户名密码不能为空!"] setDuration:2000] show];
        return;
    }
    
    [_nameText resignFirstResponder];
    [_passText resignFirstResponder];
    [_contentScroll setContentOffset:CGPointZero animated:YES];
    
//    NSData * data = nil;
//    if ([GToolUtil isMobileNumber:nameOrPhone]) {
//        data = [[[[[LoginRequestMessage builder] setPassword:pass] setPhone:nameOrPhone] build] data];
//    } else {
//        data = [[[[[LoginRequestMessage builder] setPassword:pass] setUserName:nameOrPhone] build] data];
//    }
    
    NSData * data = nil;
    if(flag == 0){
        data = [[[[[LoginRequestMessage builder] setPassword:pass] setPhone:nameOrPhone] build] data];
    } else {
        data = [[[[[LoginRequestMessage builder] setPassword:pass] setUserName:nameOrPhone] build] data];
    }
    
    if (data) {
        [_parser noCacheRequestURL:URL_UEER_LOGIN postData:data completion:^(NSData * resultData) {
            LoginResponseMessage * loginResp = [LoginResponseMessage parseFromData:resultData];
            if (loginResp && loginResp.resultCode == 0 && loginResp.userId > 0) {
                [GConfig setUserId:loginResp.userId];
                [GConfig setUserLoginInfo:[NSDictionary dictionaryWithObjectsAndKeys:loginResp.userName, @"user", loginResp.phone, @"phone", pass, @"pass", nil]];
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_LOGIN_SUCCESS object:nil];
            } else {
                [[[iToast makeText:@"登陆出错或者用户名密码错误!"] setDuration:2000] show];
            }
        } fail:^(NSError * err) {
            [[[iToast makeText:@"登陆失败!"] setDuration:2000] show];
        }];
    }
}


- (void)didFinishPwd:(PasswordFoundResponseMessage*)resp{

    if(resp != nil && [resp resultCode] == 0){
        [[[iToast makeText:@"已发送，密码稍后会以短信形式发送到你手机"] setDuration:2000] show];
        return;
    }
    [[[iToast makeText:@"服务器出错!"] setDuration:2000] show];
}
- (void)failPwd{

    [[[iToast makeText:@"服务器出错!"] setDuration:2000] show];
    
}


- (void)viewDidUnload {
    [self setNameText:nil];
    [self setPassText:nil];
    [self setContentScroll:nil];
    [self setSegmentControl:nil];
    [self setTextName:nil];
    [self setTextPwd:nil];
    [self setBtnRegister:nil];
    [self setBtnLogin:nil];
    [self setPhoneText:nil];
    [self setBtnPwd:nil];
    [super viewDidUnload];
}


#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [_contentScroll setContentOffset:CGPointMake(0, 100) animated:YES];
}


- (IBAction)actionForgetPwd:(id)sender {
    _alert = [[UIAlertView alloc] initWithTitle:@"输入您的注册手机号" message:@" " delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"发送", nil];
    [_phoneText setFrame:CGRectMake(12, 40, 260, 31)];
    if (!IPHONE_OS_EQUILORHIGHERTHAN(@"4.0")) {
        CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 110.0);
        [_alert setTransform:myTransform];
    }
    [_phoneText setText:@""];
    [_alert addSubview:_phoneText];
    [_alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if(buttonIndex != 0){
        
        NSString* text = _phoneText.text;
        if(text != nil && text.length == 11){
            [_pwdParser reqPassword:[text longLongValue]];
        } else {
            [[[iToast makeText:@"请输入正确的手机号码!"] setDuration:2000] show];
        }
    }

}
@end
